package com.qf.util;

import com.qf.bean.Employee;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.ResourceBundle;

/**
 * 2019/11/25
 * 键盘敲烂，月薪过万
 * 登高必自卑，行远必自迩。
 * 不忘初心：像初学者一样拥有一颗谦虚、开放的心态。
 * 李学峰
 */
public class   LoginInterceptor implements HandlerInterceptor {
    @Override
    //拦截器开始执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      //1判断是否匿名地址
        //专门读取proper属性文件的
        ResourceBundle anon = ResourceBundle.getBundle("anon");
        String requestURI = request.getRequestURI();
        if (anon.containsKey(requestURI)){
            return true;
        }
        //2判断session是否有值
        HttpSession session = request.getSession();
        Employee user =(Employee)session.getAttribute("user");
        if (user!=null){
            return true;
        }else {
            //3.根据结果跳转页面
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print("<script>alert('请登录');location.href='/login.jsp'</script>");
            return false;
    }
    }
    //拦截器结束执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    //拦截器无论啥都执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
